package org.lt.cj.core;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;

public class FileDownLoader {

    /**根据 url 和网页类型生成需要保存的网页的文件名
     *去除掉 url 中非文件名字符
     */
    public String getFileNameByUrl(String url, String contentType) {
        url = url.substring(7);//remove http://
        if (contentType.indexOf("html") != -1)//text/html
        {
            url = url.replaceAll("[\\?/:*|<>\".]", "_") + ".html";
            return url;
        } else//如application/pdf
        {
            return url.replaceAll("[\\?/:*|<>\".]", "_") + "." + contentType.substring(contentType.lastIndexOf("/") + 1);
        }
    }

    /**保存网页字节数组到本地文件
     * filePath 为要保存的文件的相对地址
     */
    private void saveToLocal(InputStream data, String filePath) {
        try {

            File file = new File(filePath);
            if (!file.exists()) {
                boolean success = file.createNewFile();
                if (!success) {
                    System.out.println("file not create");
//                throws  new java.io.FileNotFoundException();
                }
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(data, "GB2312"));
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            String s = "";
            while ((s = reader.readLine()) != null) {
//                System.out.println(s);
                writer.write(s);
            }
            writer.flush();
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*下载 url 指向的网页*/
    public String downloadFile(String url) {
        String filePath = null;
        /* 1.生成 HttpClinet 对象并设置参数*/
        HttpClient httpClient = new DefaultHttpClient();
        //设置 Http 连接超时 5s;

        /*2.生成 GetMethod 对象并设置参数*/
        HttpGet httpget = new HttpGet(url);
        httpget.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10");
        httpget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);


        //设置 get 请求超时 5s
//        httpget.getParams().setParameter(HttpGetParams.SO_TIMEOUT, 5000);
        //设置请求重试处理
//        httpget.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        /*3.执行 HTTP GET 请求*/
        try {
//            int statusCode 
            HttpResponse response = httpClient.execute(httpget);
            //判断访问的状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + response.getStatusLine().getStatusCode());
                filePath = null;
            }

            String headerValue = response.getFirstHeader("Content-Type").getValue();
            /*4.处理 HTTP 响应内容*/
            InputStream responseBody = response.getEntity().getContent();//读取为字节数组
            //根据网页 url 生成保存时的文件名 
            filePath = System.getProperty("user.home") + File.separator + "temp";
            File file = new File(filePath);
            if (!file.exists()) {
                boolean success = file.mkdir();
                if (success) {
                    System.out.println("hello,ok");
                }
            }
            filePath += File.separator + getFileNameByUrl(url, headerValue);
            saveToLocal(responseBody, filePath);
        } catch (IOException e) {
            // 发生网络异常
            e.printStackTrace();
        } finally {
            // 释放连接
            httpClient.getConnectionManager().shutdown();//release Connection;
        }
        return filePath;
    }
    //测试的 main 方法

    public static void main(String[] args) {
        FileDownLoader downLoader = new FileDownLoader();
        downLoader.downloadFile("http://www.163.com");
    }
}
